// var DB = require("../lib/db_pg").DB;
var DB = require("../lib/db_mysql").DB;
var config = require('../lib/config');
var resErr = require('../lib/util.js').resErr;
var md5 = require('../lib/util.js').md5;
var async = require('async');
var http_request = require('../lib/util.js').http_request;

exports.dept_list = function(req,res){
    var dept_cd = req.param('department_cd');
    var sql_text = "SELECT u.* FROM t_department u WHERE 1=1";
    var tmp_params = [];
    var i=1;
    if(dept_cd) {
        sql_text += " and upper(department_cd) like upper('" + dept_cd + "')";
    }
    
    var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
    var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
    if(req.param("sort")){
        sql_text += " order by u." + req.param("sort");
        if(req.param("dir")){
            sql_text += " " + req.param("dir");
        }
    }
    
    var db = new DB();
    db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
        if(err) return resErr(res, err);
            return res.json(result);
    });
};

exports.dept_add = function(req, res){
    // var dept_cd = req.param('department_cd');
    // if(!dept_cd) return res.json({success:false,msg:'院系代码不能为空！'});
    var dept_name = req.param('department_name');
    console.log(dept_name);
    if(!dept_name) return res.json({success:false,msg:'院系名称不能为空！'});
    var director_id = req.param('leader_id'); // 院系主任id可以为空
    if(!director_id)
        director_id = 0;
    var db = new DB();
    
    async.waterfall([
        function(cb){
            var tmp_params = [];
            var sql_text = 'select count(1) as counter from t_department where department_name = ?;';
            tmp_params.push(dept_name);
            db.query(sql_text,tmp_params,function(err,datas){
                if(err) return cb(err);
                if(datas.length > 0 && datas[0].counter > 0){
                  return cb('该院系已经存在！');
                }
                return cb(null);
            });
        }, function(cb){
            var tmp_params = [];
            var sql_text = 'insert into t_department(department_name, director_id, enable_flag) values(?,?,"Y");';
            tmp_params.push(dept_name);
            tmp_params.push(director_id);
            db.query(sql_text, tmp_params, function(err, data){
                console.log(err);
                console.log(data);
                if(err){
                    return cb(err);
                }
                return cb(null);
            });
        }
    ], function(err){ // callback
        if (err){
            return res.json({success:false,msg:JSON.stringify(err)});
        }      
        return res.json({success:true,msg:'院系添加成功！'});
    });
};

exports.dept_del = function(req, res){
    var dept_id = req.param('department_id');
    if(!dept_id) return res.json({success: false, msg: '院系代码不能为空'});
    
    var db = new DB();
    var sql_text = 'delete from t_department where department_id = ?;';
    
    var tmp_params = [];
    tmp_params.push(dept_id);
    
    db.query(sql_text, tmp_params, function(err, datas){
        console.log(datas);
        if(err){
            return resErr(res, err);
        }
        return res.json({success: true, msg: '院系删除成功'});
    });
};

exports.dept_upd = function(req, res){
    var dept_cd = req.param('department_id');
    if(!dept_cd) return res.json({success: false, msg: '院系代码不能为空'});
    var dept_name = req.param('department_name');
    if(!dept_name) return res.json({success:false,msg:'院系名称不能为空！'});
    var leader_id = req.param('leader_id');
    if (!leader_id) leader_id = '';
    
    var db = new DB();
    var sql_text = ' update t_department set department_name = ?, director_id = ? ';
    sql_text += ' where department_id = ?;';
    
    var tmp_params = [];
    tmp_params.push(dept_name);
    tmp_params.push(leader_id);
    tmp_params.push(dept_cd);
    
    db.query(sql_text, tmp_params, function(err, datas){
        console.log(datas);
        if(err){
            return resErr(res, err);
        }
        return res.json({success: true, msg: '院系信息修改成功'});
    });
};

exports.tree = function(req, res){
    var sql_text = "select *, department_name as text ";
    sql_text += " from t_department ";
    sql_text += " where enable_flag = 'Y' ";
    sql_text += " order by department_id ";

    var tmp_params = [];
    var db = new DB();

    db.query(sql_text, tmp_params, function(err, depts){
        if(err) return res.json({success:false,msg:JSON.stringify(err)});
        async.eachSeries(depts, function(item, callback){
            item.leaf = true;
            var sql_text2 = "select *, class_name as text ";
            sql_text2 += " from t_class ";
            sql_text2 += " where enable_flag = 'Y' ";
            sql_text2 += " and department_id = ? ";
            sql_text2 += " order by class_id ";

            tmp_params = [];
            tmp_params.push(item.department_id);

            db.query(sql_text2, tmp_params, function(err, classes){
                item.classes = classes;
                // item.children = classes;
                // item.leaf = false;
                if(err) return callback(err);
                return callback(null);
            });
        }, function(err){
            if(err) return res.json({success:false,msg:JSON.stringify(err)});
            // console.log(depts);
            // console.log(depts[0].children);
            return res.json(getDepartmentTree(depts));
        });
    });
}

function getDepartmentTree(depts) {
    var result = [];
    // console.log('getDepartmentTree');
    if(depts) {
      var root_children_list = [];
      depts.forEach(function(element) {
        var dept = {};
        dept.id = element.department_id;
        dept.text = element.text;
        dept.node_type = 'dept';
        dept.director_id = element.director_id;
        //dept.type = 'dept';
        dept.leaf = false;
        dept.icon = null;
        dept.children = [];
        if(element.classes && element.classes.length > 0){
        //     dept.leaf = false;
        //     dept.icon = null;
        //     dept.children = [];
            // dept.expanded = true;
            dept.leaf = false;
            element.classes.forEach(function(element2){
                var _class = {};
                _class.id = element2.class_id;
                _class.text = element2.text;
                _class.children = [];
                _class.node_type = 'class'
                _class.leader_id = element2.teacher_id;
                _class.leaf = true;
                _class.icon = null;
                dept.children.push(_class);
             });
        // }else{
        //     dept.children = null;
        }
        result.push(dept);
      });
    }
    return result;
  }